import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus, LoggerService } from "@nestjs/common";

@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  constructor(private readonly logger: LoggerService) {}
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    // 请求 响应对象
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    // http 状态码
    const status = exception.getStatus()

    // 记录日志
    this.logger.error(exception.message, exception.stack)

    response.status(status).json({
      code: status,
      timestamp: new Date().toISOString(),
      path: request.url,
      method: request.method,
      message: exception.message || exception.name,
    });
    // throw new Error('HttpExceptionFilter');
  }
}
